<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        :closable="false"
        show-icon
      >
      </el-alert>

      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form>
        <el-tabs
          @tab-click="tabClick"
          :before-leave="beforeLeave"
          tab-position="left"
          v-model="active"
        >
          <el-tab-pane label="基本信息" name='0'>
            <el-form :model="form" label-position="top" label-width="80px">
              <el-form-item label="商品名称">
                <el-input v-model="form.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格">
                <el-input type="number" v-model="form.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量">
                <el-input type="number" v-model="form.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品数量">
                <el-input type="number" v-model="form.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                <!-- {{ value }} -->
                <el-cascader
                  :props="{ value: 'cat_id', label: 'cat_name' }"
                  :options="options"
                  v-model="value"
                >
                </el-cascader>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name='1'>
            <el-form-item v-for="item in manyList" :key="item.attr_id">
              {{ item.attr_name }}<br />
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="items"
                  v-for="(items, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name='2'>
            <el-form-item v-for="item in onlyList" :key="item.attr_id">
              {{ item.attr_name }}
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="headObj"
              :on-preview="handlePreview"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <quill-editor v-model="quil"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="预览图片" :visible.sync="dialogVisible">
      <el-image :src="url"></el-image>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      quil:'',
      url: "",
      pics:[],
      dialogVisible: false,
      active: "",
      value: [],
      headObj: {
        Authorization: sessionStorage.token,
      },
      options: [],
      manyList: [],
      onlyList: [],
      form: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
      },
    };
  },
  methods: {
    //添加商品
    async add(){
      // console.log(this.manyList);
      // attrs 数组用来存储 动态参数 和 静态属性 的数据
      var attrs = [];
      //动态参数的数据 以逗号分割的形式 存放到 attrs数组中
      this.manyList.forEach(item=>{
        var obj = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(',')
        }
        attrs.push(obj)
      })
      //静态属性的数据 存放到 attrs数组中
      this.onlyList.forEach(item=>{
        var obj = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals
        }
        attrs.push(obj)
      })
      // console.log(attrs);

      //调用添加商品的接口进行添加
      var res = await this.$http.post('goods',{
        goods_name:this.form.goods_name,
        goods_price:this.form.goods_price,
        goods_number:this.form.goods_number,
        goods_weight:this.form.goods_weight,
        goods_introduce:this.quil,
        pics:this.pics,
        goods_cat:this.value.join(','),
        attrs:attrs
      })
      //判断返回的数据是否成功 给出提示信息
      this.hint(res)
    },
     //提示 成功或失败 的信息
    hint(res){
      if (res.data.meta.status == 200 ||res.data.meta.status == 201) {
        this.$message({
          showClose: true,
          message: res.data.meta.msg,
          type: "success",
        });
        this.$router.push('/goods')
      } else {
        this.$message({
          showClose: true,
          message: res.data.meta.msg,
          type: "error",
        });
      }
    },
    // 文件上传成功时的钩子
    handleSuccess(response){
      this.pics.push({'pic':response.data.tmp_path})
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      this.url = file.url;
      this.dialogVisible = true;
    },
    //用来判断用户是否填选了 分类
    beforeLeave(activeName, oldActiveName) {
      // console.log(activeName, oldActiveName);
      if (activeName === "1" && this.value.length !== 3) {
        this.$message.error("请选择分类！");
        return false;
      }
    },
    //调用接口获取 商品分类数据列表
    async getCate() {
      var { data: res } = await this.$http.get("categories");
      // console.log(res.data);
      this.options = res.data;
    },
    //当Tabs标签页切换时 要调用对应的接口获取数据显示到页面
    async tabClick() {
      if (this.active == 1) {
        var { data: res } = await this.$http.get(
          `categories/${this.value[2]}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        // console.log(res.data);
        res.data.forEach((item) => {
          // console.log(item);
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        this.manyList = res.data;
        // console.log(res);
        // console.log(this.manyList);
      }
      if (this.active == 2) {
        var { data: res } = await this.$http.get(
          `categories/${this.value[2]}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        // console.log(res.data);
        this.onlyList = res.data;
      }
    },
  },
  created() {
    this.getCate();
  },
};
</script>

<style>
.el-button{
  position: relative;
  left: 0;
  top: 0;
  cursor: pointer;
}
.quill-editor{
  height: 300px;
}
.el-alert {
  height: 30px;
  margin-bottom: 20px !important;
}
.el-tabs {
  margin-top: 20px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>